using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using ADModify.Library;
using System.Xml;
using System.DirectoryServices;
using CDOEXM;
using ActiveDs;

namespace ADModify.NET.GUI
{
	/// <summary>
	/// Summary description for Undo.
	/// </summary>
	public class frmImportMailboxRights : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button btnUndoButton;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.PictureBox pictureBox3;
		private System.Windows.Forms.Button btnUndoUndo;
		private System.Windows.Forms.Button btnUndoCancel;
		private System.Windows.Forms.ProgressBar progressBarImport;
		private System.Windows.Forms.TextBox txtMBXRightsFilePath;
		private System.Windows.Forms.CheckBox chkImportOverwrite;
		private System.Windows.Forms.CheckBox chkImportAppend;
		private System.Windows.Forms.Label label2;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public frmImportMailboxRights()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmImportMailboxRights));
			this.txtMBXRightsFilePath = new System.Windows.Forms.TextBox();
			this.btnUndoButton = new System.Windows.Forms.Button();
			this.label1 = new System.Windows.Forms.Label();
			this.pictureBox3 = new System.Windows.Forms.PictureBox();
			this.btnUndoUndo = new System.Windows.Forms.Button();
			this.btnUndoCancel = new System.Windows.Forms.Button();
			this.progressBarImport = new System.Windows.Forms.ProgressBar();
			this.chkImportOverwrite = new System.Windows.Forms.CheckBox();
			this.chkImportAppend = new System.Windows.Forms.CheckBox();
			this.label2 = new System.Windows.Forms.Label();
			this.SuspendLayout();
			// 
			// txtMBXRightsFilePath
			// 
			this.txtMBXRightsFilePath.Location = new System.Drawing.Point(16, 48);
			this.txtMBXRightsFilePath.Name = "txtMBXRightsFilePath";
			this.txtMBXRightsFilePath.Size = new System.Drawing.Size(296, 20);
			this.txtMBXRightsFilePath.TabIndex = 0;
			this.txtMBXRightsFilePath.Text = "";
			// 
			// btnUndoButton
			// 
			this.btnUndoButton.Location = new System.Drawing.Point(328, 48);
			this.btnUndoButton.Name = "btnUndoButton";
			this.btnUndoButton.TabIndex = 1;
			this.btnUndoButton.Text = "Browse";
			this.btnUndoButton.Click += new System.EventHandler(this.button1_Click);
			// 
			// label1
			// 
			this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label1.Location = new System.Drawing.Point(16, 24);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(376, 24);
			this.label1.TabIndex = 2;
			this.label1.Text = "Select the mbxrights.xml file you wish to import:";
			// 
			// pictureBox3
			// 
			this.pictureBox3.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox3.Image")));
			this.pictureBox3.Location = new System.Drawing.Point(16, 120);
			this.pictureBox3.Name = "pictureBox3";
			this.pictureBox3.Size = new System.Drawing.Size(384, 8);
			this.pictureBox3.TabIndex = 26;
			this.pictureBox3.TabStop = false;
			// 
			// btnUndoUndo
			// 
			this.btnUndoUndo.Location = new System.Drawing.Point(104, 136);
			this.btnUndoUndo.Name = "btnUndoUndo";
			this.btnUndoUndo.Size = new System.Drawing.Size(104, 23);
			this.btnUndoUndo.TabIndex = 27;
			this.btnUndoUndo.Text = "Import";
			this.btnUndoUndo.Click += new System.EventHandler(this.btnUndoUndo_Click);
			// 
			// btnUndoCancel
			// 
			this.btnUndoCancel.Location = new System.Drawing.Point(208, 136);
			this.btnUndoCancel.Name = "btnUndoCancel";
			this.btnUndoCancel.Size = new System.Drawing.Size(104, 23);
			this.btnUndoCancel.TabIndex = 28;
			this.btnUndoCancel.Text = "Cancel";
			this.btnUndoCancel.Click += new System.EventHandler(this.btnUndoCancel_Click);
			// 
			// progressBarImport
			// 
			this.progressBarImport.Location = new System.Drawing.Point(16, 168);
			this.progressBarImport.Name = "progressBarImport";
			this.progressBarImport.Size = new System.Drawing.Size(384, 23);
			this.progressBarImport.TabIndex = 29;
			// 
			// chkImportOverwrite
			// 
			this.chkImportOverwrite.Location = new System.Drawing.Point(96, 96);
			this.chkImportOverwrite.Name = "chkImportOverwrite";
			this.chkImportOverwrite.TabIndex = 30;
			this.chkImportOverwrite.Text = "Overwrite";
			this.chkImportOverwrite.CheckedChanged += new System.EventHandler(this.chkImportOverwrite_CheckedChanged);
			// 
			// chkImportAppend
			// 
			this.chkImportAppend.Checked = true;
			this.chkImportAppend.CheckState = System.Windows.Forms.CheckState.Checked;
			this.chkImportAppend.Location = new System.Drawing.Point(16, 96);
			this.chkImportAppend.Name = "chkImportAppend";
			this.chkImportAppend.Size = new System.Drawing.Size(64, 24);
			this.chkImportAppend.TabIndex = 31;
			this.chkImportAppend.Text = "Append";
			this.chkImportAppend.CheckedChanged += new System.EventHandler(this.chkImportAppend_CheckedChanged);
			// 
			// label2
			// 
			this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label2.Location = new System.Drawing.Point(16, 80);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(376, 16);
			this.label2.TabIndex = 32;
			this.label2.Text = "Select the action to take when importing Mailbox Rights:";
			// 
			// frmImportMailboxRights
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(416, 197);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.chkImportAppend);
			this.Controls.Add(this.chkImportOverwrite);
			this.Controls.Add(this.progressBarImport);
			this.Controls.Add(this.btnUndoCancel);
			this.Controls.Add(this.btnUndoUndo);
			this.Controls.Add(this.pictureBox3);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.btnUndoButton);
			this.Controls.Add(this.txtMBXRightsFilePath);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "frmImportMailboxRights";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "ADModify.NET";
			this.Closing += new System.ComponentModel.CancelEventHandler(this.frmImportMailboxRights_Closing);
			this.ResumeLayout(false);

		}
		#endregion

		private void frmImportMailboxRights_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			Application.Exit();
		}

		private void button1_Click(object sender, System.EventArgs e)
		{
			OpenFileDialog fdlg = new OpenFileDialog(); 
			fdlg.InitialDirectory = @"c:\" ; 
			fdlg.Filter = "XML Files (mbxrights.xml)|mbxrights.xml";
			fdlg.FilterIndex = 2 ; 
			fdlg.RestoreDirectory = true ; 
			if(fdlg.ShowDialog() == DialogResult.OK) 
			{ 
				txtMBXRightsFilePath.Text = fdlg.FileName ; 
			} 
		}

		private void btnUndoCancel_Click(object sender, System.EventArgs e)
		{
			Application.Exit();
		}

		private void ImportMailboxRights(bool Overwrite)
		{
			//create log file
			string RawDateTime = System.DateTime.Now.ToString();
			RawDateTime = RawDateTime.Replace(" ","").Replace("/","").Replace(":","");
			string logFileName1 = RawDateTime + ".xml";
			XmlTextWriter logWriter = new XmlTextWriter(logFileName1, null);

			LogFile log = new LogFile();
			XmlDocument docXml = new XmlDocument();
			docXml.Load("mbxrights.xml");
			XmlNodeList lstXml = docXml.GetElementsByTagName("MailboxRights");
		
			bool HaveDisplayedUserCount = false;
			int UserCount = lstXml[0].ChildNodes.Count;
			string UserDN = "";
			int ACEEntryCount;
			int CurrentUserCount = 0;  //used to track the # of the current user

			progressBarImport.Minimum=0;
			progressBarImport.Maximum=UserCount;
			progressBarImport.Step=1;


			for(int i=0;i<=UserCount-1;i++)
			{

				CurrentUserCount++;

				//increment progress bar
				progressBarImport.PerformStep();

				try
				{
					UserDN = lstXml[0].ChildNodes[i].Attributes["UserDN"].Value;
					ModifyAttributes admod = new ModifyAttributes();
										
					//It gets the users Mailbox Security Descriptor or else it gets the hose again
					DirectoryEntry ent = new DirectoryEntry(UserDN);
					IExchangeMailbox objUser = (IExchangeMailbox)ent.NativeObject;
					SecurityDescriptor sd = (SecurityDescriptor)objUser.MailboxRights;
					IADsAccessControlList dacl = (IADsAccessControlList)sd.DiscretionaryAcl;

					//First strip off all existing non-inherited mailbox rights if overwrite was specified
					if(Overwrite)
					{
						IEnumerator aceEnum = dacl.GetEnumerator();
						while(aceEnum.MoveNext())
						{
							IADsAccessControlEntry currentAce = (IADsAccessControlEntry)aceEnum.Current;
							if((currentAce.AceFlags & (int)ADS_ACEFLAG_ENUM.ADS_ACEFLAG_INHERITED_ACE)!=(int)ADS_ACEFLAG_ENUM.ADS_ACEFLAG_INHERITED_ACE)
							{
								dacl.RemoveAce(currentAce);
							}
						}
					}
				
					//number of ACEs in the log file
					ACEEntryCount = lstXml[0].ChildNodes[i].ChildNodes[1].ChildNodes.Count;

					//loop through ACEs
					for(int j=0;j<=ACEEntryCount-1;j++)
					{

						IADsAccessControlEntry newAce = new AccessControlEntryClass();

						string Trustee = lstXml[0].ChildNodes[i].ChildNodes[1].ChildNodes[j].Attributes["Trustee"].Value.ToString();
						if(Trustee!=null)
						{

							//ChildNodes[1] denotes the NotInherited node
							string[] PermissionsArray = lstXml[0].ChildNodes[i].ChildNodes[1].ChildNodes[j].Attributes["Mask"].Value.ToString().Split(' ');
							for(int k=0; k<=PermissionsArray.GetUpperBound(0);k++)
							{
								if(PermissionsArray[k]!="")
								{
									string[] SinglePermissionsArray = PermissionsArray[k].Split('|');
									string Permission = SinglePermissionsArray[0];
									bool Deny = false;
									if(SinglePermissionsArray[1]=="Denied")
									{
										Deny = true;
									}
						
									newAce.Trustee = Trustee;
									int PermissionInt = 0;

									switch(Permission)
									{
										case "ACE_MB_FULL_ACCESS":
											PermissionInt = 0x1;
											break;
										case "ACE_MB_ASSOC_EXT_ACCT":
											PermissionInt = 0x4;
											break;
										case "ACE_MB_DELETE_MB_STORAGE":
											PermissionInt = 0x10000;
											break;
										case "ACE_MB_READ_PERMISSIONS":
											PermissionInt = 0x20000;
											break;
										case "ACE_MB_CHANGE_PERMISSION":
											PermissionInt = 0x40000;
											break;
										case "ACE_MB_TAKE_OWNERSHIP":
											PermissionInt = 0x80000;
											break;
									}
		
									newAce.AccessMask = PermissionInt;
									if(!Deny)
									{
										newAce.AceType = (int)ADS_ACETYPE_ENUM.ADS_ACETYPE_ACCESS_ALLOWED;
									}
									else
									{
										newAce.AceType = (int)ADS_ACETYPE_ENUM.ADS_ACETYPE_ACCESS_DENIED;
									}
									newAce.AceFlags = 2;
									dacl.AddAce(newAce);
								}

								
						
							}
						}
					
					}

					sd.DiscretionaryAcl = dacl;
					objUser.MailboxRights = sd;
					ent.CommitChanges();
					log.LogSuccess(logWriter, UserDN, "Import Mailbox Rights", "Not Available When Importing Mailbox Rights", "Mailbox Rights Imported");
					ent.Dispose();
				}
				catch(System.Exception caught)
				{
					string FailureMessage = "ADMODIFY.ERR - " + caught.Message;
					if(FailureMessage=="ADMODIFY.ERR - Catastrophic failure")
					{
						//we failed most likely because the users mailbox store is inaccessible
						FailureMessage = "ADMODIFY.ERR - A Catastrophic failure has occured.  Please verify that the users mailbox store is online.";
					}
					if(FailureMessage=="ADMODIFY.ERR - Unspecified error")
					{
						//the user most likely doesn't have a mailbox
						FailureMessage = "ADMODIFY.ERR - An Unspecified Error has occured.  Please ensure that the user being modified has an Exchange Mailbox.";				
					}
					log.LogFailure(logWriter, UserDN, "Import Mailbox Rights", FailureMessage);
				}
				
			}



			//finish
			log.showResults();
			logWriter.Flush();
			logWriter.Close();



		}


		private void btnUndoUndo_Click(object sender, System.EventArgs e)
		{

			Cursor.Current = Cursors.WaitCursor;

			if(txtMBXRightsFilePath.Text.Length==0)
			{
				MessageBox.Show("Please Select a Log File.");
				return;
			}

			//timer
			DateTime endTime;
			TimeSpan finalCount;

			DateTime startTime = System.DateTime.Now;

			string RawDateTime = System.DateTime.Now.ToString();
			RawDateTime = RawDateTime.Replace(" ","").Replace("/","").Replace(":","");
			string logFileName = RawDateTime + ".xml";

			//import
			bool Overwrite = false;
			if(chkImportOverwrite.Checked==true)
			{
				Overwrite=true;
			}
			
			ImportMailboxRights(Overwrite);


			Cursor.Current = Cursors.Arrow;

			endTime = System.DateTime.Now;
			finalCount = endTime.Subtract(startTime);

			MessageBox.Show("Operation Completed in " + finalCount + " seconds.");
			Application.Exit();
		}

		private void chkImportAppend_CheckedChanged(object sender, System.EventArgs e)
		{
			if(chkImportAppend.Checked==true)
			{
				chkImportOverwrite.Checked=false;
			}
			else
			{
				chkImportOverwrite.Checked=true;
			}
		
		}

		private void chkImportOverwrite_CheckedChanged(object sender, System.EventArgs e)
		{
			if(chkImportOverwrite.Checked==true)
			{
				chkImportAppend.Checked=false;
			}
			else
			{
				chkImportAppend.Checked=true;
			}

		
		}
	}
}
